package com.uziot.javassist.test1;

import javassist.*;

import java.io.IOException;
import java.net.URL;

/**
 * @author shidt
 * @version V1.0
 * @className JavassistTest2
 * @date 2022-06-06 22:47:00
 * @description
 */

public class JavassistTest6 {

    public static void main(String[] args) throws CannotCompileException, IOException {

        URL resource = JavassistTest2.class.getClassLoader().getResource("");
        String file = resource.getFile();
        System.out.println("文件存储路径：" + file);

        ClassPool cp = ClassPool.getDefault();
        CtClass ctClass = cp.makeClass("com.uziot.javassist.Hello");

        //添加一个hello1的方法
        CtMethod ctMethod = new CtMethod(CtClass.voidType, "hello1", new CtClass[]{CtClass.intType, CtClass.doubleType}, ctClass);
        ctMethod.setModifiers(Modifier.PUBLIC);
        ctClass.addMethod(ctMethod);

        //添加一个int类型的，名字为value的变量
        CtField ctField = new CtField(CtClass.intType, "value", ctClass);
        ctField.setModifiers(Modifier.PRIVATE);
        ctClass.addField(ctField);

        //为value变量添加set方法
        CtMethod setValue = new CtMethod(CtClass.voidType, "setValue", new CtClass[]{CtClass.intType}, ctClass);
        setValue.setModifiers(Modifier.PUBLIC);
        //设置方法体
        setValue.setBody("this.value = $1;");

        ctClass.addMethod(setValue);

        //为value变量添加get方法
        CtMethod getValue = new CtMethod(CtClass.intType, "getValue", new CtClass[]{}, ctClass);
        getValue.setModifiers(Modifier.PUBLIC);
        //设置方法体
        getValue.setBody("return this.value;");
        ctClass.addMethod(getValue);

        ctClass.writeFile(file);
    }
}
